/*
 * AppConfig.cpp
 *
 *  Created on: 2010-4-24
 *      Author: anod
 */

#include <Module-AppConfig/AppConfig.hpp>
#include <cstddef>
#include <cstdlib>
#include <QString>
#include <Event.hpp>
#include <IOEvent.hpp>

#define DEPEND_MODULE_COUNT 0
#define HOME_ENV        "HOME"
#define CONFIG_FILENAME "/.kde/share/apps/plasma/plasmoids/kde_weather/plasmiod_weather.cfg"
using AppConfig::appConfig;
using AppConfig::moduleObj;
using AppConfig::WidgetConfig;

static void OnLoadFinish( const Event& );
static void OnLoadFailed( const Event& );

static void init(void)
{
	if(moduleObj.state == ModuleObject::MODULE_STATE_UNAVAILABLE)
	{
		QString conf_fname = getenv(HOME_ENV);
		conf_fname += CONFIG_FILENAME;
		appConfig.listenMyEvent(Event::IOEVENT_LOAD_FINISH, OnLoadFinish);
		appConfig.listenMyEvent(Event::IOEVENT_LOAD_FAILED, OnLoadFailed);
		appConfig.load(conf_fname);
	}
}

static void OnLoadFinish( const Event& event )
{
	moduleObj.state = ModuleObject::MODULE_STATE_READY;
	appConfig.nolistenMyEvent(Event::IOEVENT_LOAD_FINISH, OnLoadFinish);
	appConfig.nolistenMyEvent(Event::IOEVENT_LOAD_FAILED, OnLoadFailed);
}

static void OnLoadFailed( const Event& event )
{
	const IOEvent& e = dynamic_cast<const IOEvent&>(event);

	moduleObj.state = ModuleObject::MODULE_STATE_UNAVAILABLE;
	memset( moduleObj.last_error, 0, ERROR_MESSAGE_SIZE );
	strncpy( moduleObj.last_error, e.fileName, ERROR_MESSAGE_SIZE-1 );
	appConfig.nolistenMyEvent(Event::IOEVENT_LOAD_FINISH, OnLoadFinish);
	appConfig.nolistenMyEvent(Event::IOEVENT_LOAD_FAILED, OnLoadFailed);
}

namespace AppConfig
{

ModuleObject moduleObj = {
		name:"applet-configuration",
		dep:NULL,
		module_init:init,
		last_error:"\0",
		state:ModuleObject::MODULE_STATE_UNAVAILABLE
};

WidgetConfig appConfig = WidgetConfig();

}
